import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import {getToken, removeToken} from '@/utils/auth'
import router from "@/router";

// create an axios instance
// https://www.axios-http.cn/docs/req_config
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // `baseURL` 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL。它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000, // request timeout
  traditional: true,
  transformRequest: [
    function(data) {
      let ret = ''
      for (let it in data) {
        ret +=
          encodeURIComponent(it) +
          '=' +
          encodeURIComponent(data[it]) +
          '&'
      }
      return ret
    }
  ]
});

// request interc5eptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Token'] = getToken()

    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

    // else if (code === 500) {
    //   Message({ message: msg, type: 'error' })
    //   return Promise.reject(new Error(msg))
    // } else if (code === 601) {
    //   Message({ message: msg, type: 'warning' })
    //   return Promise.reject('error')
    // } else if (code !== 200) {
    //   Notification.error({ title: msg })
    //   return Promise.reject('error')
    // } else {
    //   return res.data
    // }


    // if the custom code is not 20000, it is judged as an error.
    if (response.status !== 200) {
      /*必定有错误*/
      Message({
        message: response.data.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(new Error(response.data.msg || 'Error'))
    } else {

      //请求不正常
      if (response.data.code === 401) {
        // token问题
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
          store.dispatch('user/logout').then(() => {
            location.href = '/login';
          })
        }).catch(() => {

        });
        /*必定有错误*/
        Message({
          message: response.data.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })

        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
      }


      /**
       * 所有500响应都给错误提示
       */
      if (response.data.code===500){
        Message({
          message: response.data.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(response.data.msg || 'Error'))
      }

      return response
    }
  },
  error => {
    // 遇见所有错误信息就跳转到登陆页面
    console.log('err' + error) // for debug

    switch (error.response.status) {
      case 500:
        // do something...
        break
      case 404:
        router.push({
          path:'/404'
        })
        break
      case 401: {

        router.push({
          path:'/login'
        })
        break;
      }
    }

    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error)
  }
)

export default service
